<template>
    <view class="login">
        <!-- 这里通过密码登录 -->
        <view class="content">
            <!-- 头部logo -->
            <view class="header">
                <image src="../../../static/logo.png"></image>
            </view>
            <!-- 密码登录的主体表单 -->
            <view class="main" v-if=" loginWay == '邮箱验证登录'">
                <wInput v-model="email_or_username" type="text" maxlength="12" placeholder="邮箱/用户名"></wInput>
                <wInput v-model="password" type="password" maxlength="12" placeholder="密码"></wInput>
                <wButton bgColor="#354E44" text="登 录" :rotate="isRotate" @click.native="startLogin()"></wButton>
            </view>

            <!-- 邮箱验证登录的主体表单 -->
            <view class="main" v-if=" loginWay == '账户密码登录'">
                <wInput v-model="email" type="email" maxlength="16" placeholder="邮箱"></wInput>
                <wInput v-model="verCode" type="text" maxlength="6" placeholder="请输入验证码" isShowCode ref="runCode"
                    @setCode="getVerCode()"></wInput>

                <wButton bgColor="#354E44" text="登 录" :rotate="isRotate" @click.native="startLoginByEmail()"></wButton>
            </view>
            <!-- 底部信息 -->
            <view class="footer">
                <text @click="changeLoginWay()" open-type="navigate">{{loginWay}}</text>
                <text>|</text>
                <text @click="to_register()" open-type="navigate">注册账号</text>
            </view>
        </view>
    </view>
</template>

<script>
    var _this;
    import wInput from '@/components/watch-login/watch-input.vue' //input
    import wButton from '@/components/watch-login/watch-button.vue' //button
    import userApi from '@/api/user/index.js'
    import utils from '@/common/utils.js'

    export default {
        data() {
            return {
                logoImage: '',
                email_or_username: 'admin', //邮箱/用户名
                password: '123456', //密码
                isRotate: false, //是否加载旋转
                user: {},
                loginWay: '邮箱验证登录',
                verCode: '',
                email: ''
            };
        },
        components: {
            wInput,
            wButton,
        },
        methods: {
            //跳到注册页面
            to_register() {
                setTimeout(() => {
                    uni.navigateTo({
                        url: '/pages/user/register/register'
                    })
                }, 1000)
            },
            //邮箱验证登录
            changeLoginWay() {
                if (this.loginWay == '邮箱验证登录') {
                    this.loginWay = '账户密码登录'
                } else if (this.loginWay == '账户密码登录') {
                    this.loginWay = '邮箱验证登录'
                }
            },
            //获取验证码
            getVerCode() {
                if (!utils.checkEmail(this.email) || this.email.length < 16) {
                    uni.showToast({
                        title: '邮箱格式错误',
                        icon: 'none'
                    });
                    return false;
                } else if (utils.checkEmail(this.email) && this.email.length === 16) {
                    //触发倒计时（一般用于请求成功验证码后调用）
                    this.$refs.runCode.$emit('runCode');
                    setTimeout(function() {
                        this.$refs.runCode.$emit('runCode', 0);
                    }, 3000)
                    userApi.getEmailCode(this.email).then(res => {
                        if (res.success == true) {
                            uni.showToast({
                                icon: 'none',
                                position: 'bottom',
                                title: '登录邮箱输入获得的验证码'
                            });
                            resolve(true)
                        } else {
                            rej(false)
                        }
                    })
                }
            },
            loginByEmail() {
                return new Promise((resolve, rej) => {
                    userApi.loginByEmail_Code({
                        verCode: this.verCode,
                        email: this.email
                    }).then(res => {
                        console.log(res)
                        if (res.success == true) {
                            uni.clearStorageSync();
                            uni.setStorageSync("token", res.token);
                            resolve(true)
                        } else {
                            rej(false)
                        }
                    })
                })
            },
            async startLoginByEmail() {
                var _this = this;
                //登录
                if (this.isRotate) {
                    //判断是否加载中，避免重复点击请求
                    return false;
                }
                if (this.verCode.length != 6) {
                    uni.showToast({
                        icon: 'none',
                        position: 'bottom',
                        title: '验证码不正确'
                    });
                    return false;
                }
                _this.isRotate = true
                setTimeout(function() {
                    _this.isRotate = false
                }, 3000)
                //以同步的方式写异步操作
                var result = await this.loginByEmail();
                if (result) {
                    await this.getUserInfo();
                } else {
                    uni.showToast({
                        title: "登录失败,请检查用户名和密码!"
                    })
                }
            },

            //以下都是密码登录
            login() {
                return new Promise((resolve, rej) => {
                    userApi.loginByEmail({
                        username: this.email_or_username,
                        password: this.password
                    }).then(res => {
                        console.log(res)
                        if (res.success == true) {
                            // 清除旧信息
                            uni.clearStorageSync();
                            uni.setStorageSync("token", res.token);
                            // console.log(res.data.token)
                            resolve(true)
                        } else {
                            rej(false)
                        }
                    })
                })
            },
            getUserInfo() {
                return new Promise((resolve, reject) => {
                    userApi.getUserInfo()
                        .then(res => {
                            console.log('login/获取用户信息方法', res)
                            if (res.status == 0) {
                                uni.setStorageSync("user", res.data);
                                uni.showToast({
                                    title: "登录成功,1s后跳转到我的页面"
                                })
                                setTimeout(() => {
                                    uni.switchTab({
                                        url: '/pages/user/user'
                                    })
                                }, 1000)
                                resolve()
                            } else {
                                reject()
                            }
                        })
                })
            },
            async startLogin() {
                var _this = this;
                //登录
                if (this.isRotate) {
                    //判断是否加载中，避免重复点击请求
                    return false;
                }
                if (this.email_or_username.length == "") {
                    uni.showToast({
                        icon: 'none',
                        position: 'bottom',
                        title: '用户名不能为空'
                    });
                    return;
                }
                if (this.password.length < 6 || this.password.length > 12) {
                    uni.showToast({
                        icon: 'none',
                        position: 'bottom',
                        title: '密码长度在6~12位'
                    });
                    return;
                }
                _this.isRotate = true
                setTimeout(function() {
                    _this.isRotate = false
                }, 3000)
                //以同步的方式写异步的操作流程
                var result = await this.login();
                console.log(result)
                if (result) {
                    await this.getUserInfo();
                } else {
                    uni.showToast({
                        title: "登录失败,请检查用户名和密码!"
                    })
                }
            },
        }
    }
</script>

<style scoped>
    @import url("../../../components/watch-login/css/icon.css");
    @import url("../../../static/css/login_form.css");
</style>
